// 1.引入常态化样式表
require("../../assets/css/normalize.css");
// 2.引入重置样式表
require("../../assets/css/reset.css");
// 3.引入公共样式
require("../../assets/css/common.css");
// 4.引入字体图标样式
require("../../assets/fonts/iconfont.css");
// 5.引入当前页样式
require("./register.less");

// 引入模块
const CaptchaMini = require("captcha-mini");
const dom = require("../../utils/dom.js");
const axios = require("../../utils/axios.js");

window.addEventListener("DOMContentLoaded", function () {
	// 创建验证码
	let captcha = new CaptchaMini();
	let code = "";
	captcha.draw(dom.get("#captcha"), (r) => {
		code = r.toLowerCase();
	});

	// 表单验证
	dom.get("#reg-btn").addEventListener("click", function () {
		let error = dom.get("#error");

		// 手机号验证
		let tel = dom.get("#tel").value;
		let reg = /^1[356789]\d{9}$/i;
		if (reg.test(tel)) {
			error.textContent = "";
		} else {
			error.textContent = "手机号输入错误";
			return;
		}

		// 验证码
		let codenode = dom.get("#code").value.toLowerCase();
		if (code === codenode) {
			error.textContent = "";
		} else {
			error.textContent = "验证码错误";
			return;
		}

		// 密码验证
		let pwd = dom.get("#pwd").value;
		if (pwd.length >= 6) {
			error.textContent = "";
		} else {
			error.textContent = "密码至少六位";
			return;
		}

		// 密码二次验证
		let pwd2 = dom.get("#pwd2").value;
		if (pwd2 === pwd) {
			error.textContent = "";
		} else {
			error.textContent = "两次输入密码不一致";
			return;
		}

		//所有验证都通过再发送请求
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				account: tel,
				password: pwd,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					location.href = "login.html";
					alert("恭喜你，注册成功！");
				} else {
					alert("注册失败，" + res.data.message);
				}
			});
	});
});
